/*
 * @Descripttion:
 * @version:
 * @Author: qingzi
 * @Date: 2022-04-20 17:21:04
 * @LastEditors: qingzi
 * @LastEditTime: 2023-04-17 17:21:35
 */
import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { localStorage, sessionStorage } from "@/utils/storage";
// import useStore from "@/store";
import { useRouter } from 'vue-router';
import { PROJECTINFO, TOKEN,APPID } from "@/utils/const"
import { userStoreHook } from "@/store/login";
// import {useStore} from "@/store"
// const store=useStore()

//  baseURL地址需保持和代理地址一致  *********重要信息zhw  文件上传
// export const baseURL=`http://127.0.0.1:4523/m1/2510743-0-default`
// export const baseURL = `http://10.10.0.201:8219`
// export const baseURL = `http://10.10.0.74:8219` // zcy
// export const baseURL = `http://114.116.13.1:8219` // 测试环境
// export const baseURL=`http://10.10.0.205:8082` /// 王杰
// export const baseURL = `http://10.10.0.121:8221`
export const baseURL = `http://10.10.0.201:8221`

// export const baseURL = `http://10.10.0.233:8080`
// 创建 axios 实例
const service = axios.create({
  baseURL, // 正式
  timeout: 50000,
  // headers: {'Content-Type': 'application/json;charset=utf-8','token':sessionStorage.get(TOKEN) || userStoreHook().token},
  headers: {'Content-Type': 'application/json;charset=utf-8'}
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }

    // console.log(userStoreHook(),'userStoreProInfoHook().getProjectId()', localStorage.get(PROJECTINFO) , userStoreHook().projectInfo,'sessionStorage.get(TOKEN) || userStoreHook().token',sessionStorage.get(TOKEN) , userStoreHook().token)


    // const { user } = useStore();
    let token =sessionStorage.get(TOKEN)  || userStoreHook().token || 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIn0.H7Sd0g8lQNzyyN7UFgqGxVKRUeGZCtler8k-0sNs4KM'
    // let token =sessionStorage.get(TOKEN)  || userStoreHook().token

    // if (token && JSON.stringify(token)!=="{}") {
      // config.headers.Authorization = `${localStorage.get("token")}`;
    
    // let appid=JSON.stringify(userStoreHook().appId)==="{}"?"1":(userStoreHook().appId || sessionStorage.get(APPID) )
    let appid=JSON.stringify(userStoreHook().appId || sessionStorage.get(APPID))
    
    
      config.headers.Authorization = JSON.stringify(token)==="{}"?"":token;
      config.headers.app_id = appid
     config.headers.workspace_id= localStorage.get(PROJECTINFO).code  || userStoreHook().projectInfo.code
    //  config.headers.workspace_id= '7cba634b297a4f52a7b37c7e64c4c17e'
    // }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;

    // return response.data
    if (code == '200' || code == '20005' || code == '20006' || code===0) {
      return response.data;
    } else {
      if (code === 401) {
        // token 过期\
        const router = useRouter();
        // router.push('/');

        // localStorage.clear(); // 清除浏览器全部缓存
        window.location.href = '/'; // 跳转登录页
        ElMessageBox.alert('当前页面已失效，请重新登录', '提示', {});
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }

      ElMessage({
        message: msg || "系统出错",
        type: "error",
      });
      return Promise.reject(new Error(msg || "Error"));
    }
  },
  (error: any) => {
    const { code, msg } = error.response.data;
    // if (code === 2022) {
    // localStorage.clear(); // 清除浏览器全部缓存
    // window.location.href = "/"; // 跳转登录页
    // ElMessageBox.alert("当前页面已失效，请重新登录", "提示", {});
    // } else {
    ElMessage({
      message: msg || "系统出错",
      type: "error",
    });
    // }
    // router.push("/")
    return Promise.reject(new Error(msg || "Error"));
  }
);

// 导出 axios 实例
export default service;
